<template>
  <div class="playbox">
    <!-- 迷你窗口 -->
    <div class="mini-player" v-show="$store.state.playflag">
      <div class="control_win" @click="hidemini">
        <span class="iconfont icon-arrow-down"></span>
      </div>
      <div class="mess">
        <img
          :src="
            musicData.pic ||
            'https://p1.music.126.net/1tSJODTpcbZvNTCdsn4RYA==/109951165034950656.jpg'
          "
          alt=""
          :class="[!playState ? 'paused' : '', 'imgs']"
          @click="playView = true"
        />
        <div class="song">
          <p>{{ musicData.name || "演员" }}</p>
          <p>{{ "薛之谦" | authorFn(musicData.author) }}</p>
        </div>
      </div>
      <div class="control">
        <audio :src="srcU" ref="au"></audio>
        <span
          class="iconfont icon-bofang pl"
          @click="play"
          v-show="!playState"
        ></span>
        <span
          class="iconfont icon-zanting pl"
          @click="play"
          v-show="playState"
        ></span>
        <span class="iconfont icon-menu menu" @click="showPopup"></span>
        <!-- 列表内容 -->
        <van-popup
          v-model="show"
          round
          position="bottom"
          :style="{ height: '30%' }"
        >
          <div class="current">
            <div class="col">
              <div>
                <span class="iconfont icon-xunhuan" v-show="playmode == 'loop'"
                  >顺序播放({{ list.length }})</span
                >
                <span class="iconfont icon-icon-8" v-show="playmode != 'loop'"
                  >随机播放({{ list.length }})</span
                >
              </div>
            </div>
            <div class="content">
              <li v-for="(item, index) in list" :key="index">
                <div
                  @click="selectM(item.id)"
                  :class="[
                    { active: item.id == id },
                    { 'icon-weibiaoti-1-46': item.id == id },
                    'iconfont',
                  ]"
                >
                  {{ item.name }}
                </div>
                <span
                  class="iconfont icon-close"
                  @click="delItem(item.id)"
                ></span>
              </li>
            </div>
            <div @click="closebtn" class="closebtn">关闭</div>
          </div>
        </van-popup>
      </div>
    </div>
    <!-- 播放器 -->
    <div class="de-player" v-if="playView">
      <div class="mask"></div>
      <span
        class="iconfont icon-arrow-down close"
        @click="playView = false"
      ></span>
      <div class="title">
        <p>{{ musicData.name || "演员" }}</p>
        <p>{{ "薛之谦" | authorFn(musicData.author) }}</p>
      </div>
      <div class="content">
        <!-- 音乐磁盘 -->
        <div class="imgs" v-show="!lyricShow" @click="lyricShow = !lyricShow">
          <img
            :src="
              musicData.pic ||
              'https://p1.music.126.net/1tSJODTpcbZvNTCdsn4RYA==/109951165034950656.jpg'
            "
            alt=""
            :class="[!playState ? 'paused' : '']"
          />
        </div>
        <!-- 歌词界面 -->
        <div class="lyric" v-show="lyricShow" @click="lyricShow = !lyricShow">
          <ul ref="lyB" :style="{ top: ulTop }">
            <li class="active" v-show="!lyricData">该歌曲暂时没有歌词</li>
            <li
              v-for="(item, index) in lyricData"
              :key="index"
              :class="{ active: currentRow == index }"
            >
              {{ item.ly }}
            </li>
          </ul>
        </div>
      </div>
      <div class="range">
        <span class="curTime">{{ currentTime | ftime }}</span>
        <van-slider
          v-model="value"
          bar-height="4px"
          active-color="#d54338"
          button-size="15px"
          inactive-color="#565351"
          @change="sliderTime"
        />
        <span class="alltime">{{ duration | ftime }}</span>
      </div>
      <div class="control">
        <li @click="Smode">
          <span class="iconfont icon-icon-6" v-show="playmode == 'loop'"></span>
          <span class="iconfont icon-icon-8" v-show="playmode == 'rand'"></span>
        </li>
        <li @click="prev">
          <span class="iconfont icon-icon-4"></span>
        </li>
        <li @click="play">
          <!-- 暂停播放按钮切换 -->
          <span class="iconfont icon-icon-1" v-show="!playState"></span>
          <span class="iconfont icon-icon-5" v-show="playState"></span>
        </li>
        <li @click="next">
          <span class="iconfont icon-icon-2"></span>
        </li>
        <li @click="lova">
          <span :class="['iconfont', 'icon-xin', { love: flag }]"></span>
        </li>
      </div>
    </div>
  </div>
</template>

<script>
import { getsong, getlyric } from "../api/base/songurl";
import { Notify } from "vant";
export default {
  data() {
    return {
      playState: false,
      srcU: `http://m8.music.126.net/20210415174246/7eafdf96d737a79b7705864548c44b40/ymusic/e7c5/84f9/897e/a897fda63f7e9f788eac7abbc0bf8602.mp3`,
      show: false, // 列表展示状态
      id: 32507038, // 当前播放音频id 默认演员
      value: 0, // 进度条百分比
      playView: false, // 播放视图展示状态
      duration: null, // 当前音频总时间
      currentTime: null, // 当前播放的时间
      playmode: "loop", // 播放模式
      lyricShow: false, // 歌词界面展示状态
      lyricData: null, //歌词数据
      currentRow: 0, // 初始高亮歌词
      ulTop: "30vh", // 控制歌词界面滚动高度
      timer: null, //定时器
      fnindex: 1, // 功能标识 1：下一首 0：上一首
      endflag: 0,
    };
  },
  methods: {
    showPopup() {
      // 插件列表展开状态
      this.show = true;
    },
    closebtn() {
      // 关闭播放列表
      this.show = false;
    },
    selectM(id) {
      //播放列表选择歌曲
      let da = this.list.filter((item) => {
        return item.id == id;
      });
      this.$store.commit("curListFn", da[0]);
    },
    sliderTime(event) {
      //进度条设置时间
      this.$refs.au.removeEventListener("timeupdate", () => {});
      let setTime = (event / 100) * this.duration;
      this.$refs.au.currentTime = setTime;
    },
    play() {
      if (this.playState) {
        clearInterval(this.timer);
        this.playState = false;
        // 控制音乐
        this.$refs.au.pause();
      } else {
        this.interval();
        this.playState = true;
        // 控制音乐
        this.$refs.au.play();
      }
    },
    delItem(id) {
      // 在播放列表中删除点击的歌曲
      this.list.filter((item, index) => {
        if (item.id == id) {
          this.list.splice(index, 1);
          return true;
        }
        return true;
      });
    },
    prev() {
      this.fnindex = 0;
      if (this.list.length == 1) {
        Notify({
          type: "primary",
          message: "当前播放列表只有一首歌，已为你重新播放",
          duration: 1000,
        });
        this.$refs.au.load();
        this.$refs.au.play();
        return true;
      }
      if (this.list) {
        this.$refs.au.pause();
        // 上一曲
        let prevIndex = null;
        this.list.forEach((item, index) => {
          if (item.id == this.id) {
            prevIndex = index - 1;
            return true;
          }
        });

        if (prevIndex >= 0) {
          // this.resetSetItem.save("curList", this.list[prevIndex]); // 保存当前点击的音乐信息到sessionstorage上
          this.$store.commit("curListFn", this.list[prevIndex]);
        } else {
          prevIndex = this.list.length - 1;
          this.$store.commit("curListFn", this.list[prevIndex]);
          // this.resetSetItem.save("curList", this.list[prevIndex]); // 保存当前点击的音乐信息到sessionstorage上
        }
        this.interval();
      }
    },
    next() {
      this.fnindex = 1;
      if (this.list) {
        this.$refs.au.pause();
        if (this.playmode == "loop") {
          // 列表循环播放 下一首
          let nextIndex = null;
          this.list.forEach((item, index) => {
            if (item.id == this.id) {
              if (this.list.length == 1) {
                Notify({
                  type: "primary",
                  message: "当前播放列表只有一首歌，已为你重新播放",
                  duration: 1000,
                });
                this.$refs.au.load();
                this.$refs.au.play();
              } else {
                nextIndex = index + 1;
              }
              return true;
            }
          });
          if (nextIndex < this.list.length - 1) {
            this.$store.commit("curListFn", this.list[nextIndex]);
          } else {
            nextIndex = 0;
            this.$store.commit("curListFn", this.list[nextIndex]);
          }
        } else {
          // 随机播放
          let index = Math.floor(Math.random() * this.list.length);
          this.$store.commit("curListFn", this.list[index]);
        }
      }
    },
    Smode() {
      // 播放模式  列表循环播放 单曲播放
      if (this.playmode == "loop") {
        this.playmode = "rand";
      } else {
        this.playmode = "loop";
      }
    },
    interval() {
      this.ulTop = "30vh";
      clearInterval(this.timer);
      this.timer = setInterval(() => {
        // 控制歌词自动对齐滚动
        if (this.lyricData) {
          for (let i = 0; i < this.lyricData.length; i++) {
            if (this.currentTime == this.lyricData[i].time) {
              this.currentRow = i;
              this.ulTop = -i * 6 + 30 + "vh"; // 加6vh 是因为li高度是6vh
              // console.log("dddd");
              break;
            }
          }
        }
      }, 999);
    },
    hidemini() {
      this.$store.commit("playflagFn");
    },
    lova() {
      this.$store.commit("loveFn");
    },
  },
  created() {
    this.$store.commit("playflagFn", false);
    let id = this.$store.state.curList.id;
    if (id) {
      // 刷新时 检查vuex有没有存到id 没有用默认 有就更新数据
      getsong({ id: id }).then((data) => {
        if (data.code == 200) {
          //  获取音乐url
          this.srcU = data.data[0].url;
          getlyric({ id: id }).then((data) => {
            // 获取歌词数据
            if (data.code == 200) {
              if (data.lrc) {
                let d = data.lrc.lyric.split("\n");
                // 处理歌词数据
                let temp = Array(d.length);
                d.forEach((item, index) => {
                  let t = item.slice(0, item.indexOf("]") + 1);
                  let m = t.slice(1, t.indexOf(":"));
                  let s = t.slice(t.indexOf(":") + 1, t.length - 1);
                  let seconds = Math.floor(m * 60 + Number(s));

                  temp[index] = {
                    time: seconds,
                    ly: item.slice(item.indexOf("]") + 1),
                  };
                });
                // 歌词赋值
                this.lyricData = temp;
              }
            } else {
              this.lyricData = null;
            }
          });
        }
      });
    }
    if (this.$store.state.loginflag && this.$store.state.playflag) {
      this.$refs.au.addEventListener("timeupdate", () => {
        this.duration = this.$refs.au.duration;
        // 页面当前时间显示设置
        this.currentTime = Math.floor(this.$refs.au.currentTime);
        // 进度条设置
        this.value = (this.currentTime / this.duration) * 100;
      });
      this.interval(); // 歌词滚动定时器
      getlyric({ id: this.id }).then((data) => {
        // 获取歌词数据
        if (data.code == 200) {
          let d = data.lrc.lyric.split("\n");
          // 处理歌词数据
          let temp = Array(d.length);
          d.forEach((item, index) => {
            let t = item.slice(0, item.indexOf("]") + 1);
            let m = t.slice(1, t.indexOf(":"));
            let s = t.slice(t.indexOf(":") + 1, t.length - 1);
            let seconds = Math.floor(m * 60 + Number(s));

            temp[index] = {
              time: seconds,
              ly: item.slice(item.indexOf("]") + 1),
            };
          });
          // 歌词赋值
          this.lyricData = temp;
          // console.log(temp);
        }
      });
    }
  },
  computed: {
    musicData() {
      return this.$store.state.curList;
    },
    list() {
      return this.$store.state.allList;
    },
    flag() {
      let love = this.$store.state.love;
      let tt = false;
      if (love.length) {
        tt = love.some((item) => {
          if (item.id == this.musicData.id) {
            return true;
          }
        });
      }
      return tt;
    },
  },
  watch: {
    musicData: {
      handler() {
        this.id = this.musicData.id;
        document.title = this.musicData.name;
        getsong({ id: this.id }).then((data) => {
          if (data.code == 200) {
            // 处理没有url的情况
            if (!data.data[0].url) {
              this.endflag += 1;
              if (this.endflag < this.list.length) {
                // 判断功能标识 是点击了上一首还是下一首 0 或 1
                if (this.fnindex) {
                  Notify({
                    type: "primary",
                    message: "当前歌曲没有资源，已为你切换到下一首",
                    duration: 1000,
                  });
                  this.next();
                  if (this.$refs.au) {
                    this.playState = true; // 点击时切换播放图标
                    this.interval(); // 歌词滚动定时器
                    this.duration = this.$refs.au.duration;
                    this.$refs.au.play();
                    this.$refs.au.removeEventListener("timeupdate", null);
                    this.$refs.au.addEventListener("timeupdate", () => {
                      if (this.$refs.au) {
                        this.duration = this.$refs.au.duration;
                        // 页面当前时间显示设置
                        this.currentTime = Math.floor(
                          this.$refs.au.currentTime
                        );
                        // 进度条设置
                        this.value = (this.currentTime / this.duration) * 100;
                      }
                    });
                  }
                } else {
                  Notify({
                    type: "primary",
                    message: "当前歌曲没有资源，已为你切换到上一首",
                    duration: 1000,
                  });
                  this.prev();
                }
              } else {
                Notify({
                  type: "primary",
                  message: "没有歌曲播放",
                  duration: 3000,
                });
              }
              return false;
            } else {
              this.endflag = this.endflag - 1;
            }
            //  获取音乐url
            this.srcU = data.data[0].url;
            this.$refs.au.oncanplay = () => {
              this.playState = true; // 点击时切换播放图标
              this.interval(); // 歌词滚动定时器
              this.duration = this.$refs.au.duration;
              this.$refs.au.play();
              this.$refs.au.removeEventListener("timeupdate", null);
              this.$refs.au.addEventListener("timeupdate", () => {
                if (this.$refs.au) {
                  this.duration = this.$refs.au.duration;
                  // 页面当前时间显示设置
                  this.currentTime = Math.floor(this.$refs.au.currentTime);
                  // 进度条设置
                  this.value = (this.currentTime / this.duration) * 100;
                }
              });

              getlyric({ id: this.id }).then((data) => {
                // 获取歌词数据
                if (data.code == 200) {
                  if (data.lrc) {
                    let d = data.lrc.lyric.split("\n");
                    // 处理歌词数据
                    let temp = Array(d.length);
                    d.forEach((item, index) => {
                      let t = item.slice(0, item.indexOf("]") + 1);
                      let m = t.slice(1, t.indexOf(":"));
                      let s = t.slice(t.indexOf(":") + 1, t.length - 1);
                      let seconds = Math.floor(m * 60 + Number(s));

                      temp[index] = {
                        time: seconds,
                        ly: item.slice(item.indexOf("]") + 1),
                      };
                    });
                    // 歌词赋值
                    this.lyricData = temp;
                  } else {
                    this.lyricData = null;
                  }
                }
              });
            };
          }
          this.$refs.au.onended = () => {
            // 结束播放 下一首
            this.next();
          };
        });
      },
      deep: true,
    },
    list: {
      handler() {
        this.endflag = 0;
      },
      deep: true,
    },
  },
  filters: {
    authorFn(old, newd) {
      if (newd) {
        let str = "";
        newd.forEach((item) => {
          str = str + item.name + " / ";
        });
        str = str.substr(0, str.length - 2);
        return str;
      } else {
        return "薛之谦";
      }
    },
    ftime(time) {
      let t = "00:00";
      if (time) {
        let m = parseInt(time / 60);
        m = m < 10 ? "0" + m : m;
        let s = parseInt(time % 60);
        s = s < 10 ? "0" + s : s;
        t = "" + m + ":" + s;
      }
      return t;
    },
  },
  beforeDestroy() {
    // 销毁清除定时器
    clearInterval(this.timer); //清除定时器
  },
};
</script>

<style lang="less">
.mini-player {
  position: fixed;
  bottom: 0;
  width: 100vw;
  height: 70px;
  max-width: 640px;
  box-sizing: border-box;
  z-index: 999;
  background-color: rgba(255, 255, 255, 0.891);
  box-shadow: 0 0px 5px 2px #ccc;
  padding: 10px 8px;
  display: flex;
  font-size: 4vw;
  .control_win {
    position: absolute;
    bottom: 100%;
    right: 0;
    background-color: #fefefe;
    box-shadow: 0 -4px 5px -1px #ccc;
    width: 10vw;
    height: 2vh;
    text-align: center;
    line-height: 2vh;
    span {
      color: black;
    }
  }
  .mess {
    display: flex;

    width: 75%;
    img {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      background-color: red;
      align-self: center;
      &.imgs {
        animation: rotate 20s linear infinite;
      }
      &.paused {
        animation-play-state: paused;
      }
    }
    .song {
      margin-left: 10px;
      padding-top: 5px;
      p {
        &:nth-child(2) {
          color: rgb(63, 59, 59);
          font-size: 3vw;
        }
      }
    }
  }
  .control {
    flex: 1;
    text-align: center;
    padding-top: 3px;
    span {
      font-size: 10vw;
      margin: 0 3px;
      color: #6e6f6f;
    }
  }
}
.de-player {
  width: 100vw;
  max-width: 640px;
  position: fixed;
  top: 0;
  bottom: 0;
  // background-color: rgb(167, 220, 241);
  background: linear-gradient(45deg, #a18b8b, skyblue);
  color: white;
  z-index: 999;
  span.close {
    position: absolute;
    width: 15vw;
    height: 15vw;
    line-height: 15vw;
    text-align: center;
    font-size: 6vw;
  }
  .title {
    width: 100vw;
    max-width: 640px;
    padding-top: 3vw;
    p {
      text-align: center;
      font-size: 5vw;
      font-weight: bolder;
      padding: 0 20vw;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      &:nth-child(2) {
        font-size: 4vw;
        font-weight: inherit;
      }
    }
  }
  .content {
    width: 100vw;
    max-width: 640px;
    height: 65vh;
    position: relative;
    .imgs {
      width: 300px;
      height: 300px;
      // width: 80vw;
      // height: 80vw;
      border-radius: 50%;
      // background-color: skyblue;
      background: linear-gradient(45deg, #a18b8b, skyblue);
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      padding: 15px;
      box-sizing: border-box;
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        animation: rotate 20s linear infinite;
        &.paused {
          animation-play-state: paused;
        }
      }
    }
    .lyric {
      // border: 1px solid red;
      height: 80%;
      box-sizing: border-box;
      overflow: hidden;
      position: relative;
      top: 36px;
      //歌词界面
      ul {
        width: 100%;
        position: absolute;
        // top: 30vh;
        transition: all 1s;
        li {
          height: 6vh;
          text-align: center;
          font-size: 4vw;
          color: rgba(255, 255, 255, 0.3);
          padding: 0 1vw;
          &.active {
            color: white;
            font-weight: bolder;
          }
        }
      }
    }
  }
  .range {
    height: 5vh;
    display: flex;
    justify-content: space-between;
    align-items: center;
    & > span {
      font-size: 3vw;
      margin: 0 20px;
    }
    .van-slider__button {
      position: relative;
    }
  }
  .control {
    margin: 20px;
    display: flex;
    justify-content: space-around;
    & > li {
      list-style: none;
      // width: 50px;
      // height: 50px;
      text-align: center;
      span {
        font-size: 10vw;
        &.love {
          color: red;
          font-weight: bolder;
        }
      }
    }
  }
}
@keyframes rotate {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}
// 当前播放列表
.current {
  background-color: #f2f3f4;
  position: relative;
  padding: 8px;
  // height: 100%;
  box-sizing: border-box;
  .col {
    span {
      font-size: 5vw;
    }
  }
  .content {
    padding: 5px;
    margin-bottom: 36px;
    li {
      background-color: #f2f3f4;
      display: flex;
      height: 1.125rem;
      line-height: 1.125rem;
      justify-content: space-between;
      & > div {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      & > div.active {
        color: rgb(255, 38, 0);
      }
      span {
        font-size: 4vw;
        color: red;
        font-weight: bolder;
      }
    }
  }
  .closebtn {
    background-color: #f2f3f4;
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 36px;
    line-height: 36px;
    color: #666;
    font-size: 4vw;
  }
}
.van-popup--bottom.van-popup--round {
  height: 45% !important;
  background-color: #f2f3f4;
}
.van-cell--clickable {
  padding: 0;
}
.van-cell__left-icon,
.van-cell__right-icon {
  display: none !important;
  background-color: red;
}
</style>